import {
  OrderStatus
} from '../config';
import {
  fetchOrders,
  fetchOrdersCount,
} from '../../../services/order/orderList';
import {
  cosThumb
} from '../../../utils/util';
import {
  getMyOrderList,
  cancelOrder,
  getPreOrder,
} from '../../../api/index';

Page({
  page: {
    size: 10,
    num: 1,
  },

  data: {
    tabs: [{
        key: -1,
        text: '全部订单'
      },
      {
        key: OrderStatus.PENDING_PAYMENT,
        text: '待支付',
        info: 1
      },
      {
        key: OrderStatus.PENDING_DELIVERY,
        text: '待使用',
        info: 2
      },
      {
        key: OrderStatus.COMPLETE,
        text: '已完成',
        info: 3
      },
      {
        key: OrderStatus.PENDING_RECEIPT,
        text: '已退款',
        info: 4
      },
    ],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: '',
    backRefresh: false,
    status: -1,
    allOrderList: [],
    waitOrder: [],
    waitUse: [],
    finshList: [],
    refoundList: [],
    cancelList: [],
    failList: [],
    outTimeList: [],
    refoundingList: [], //退款中
    orderId: null,
  },

  onLoad(query) {
    console.log(parseInt(query.status), 'parseInt(query.status)')
    let status = parseInt(query.status);
    console.log(this.data.tabs, ' this.data.tabs')
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : status == 60 ? status : -1;
    console.log(status, 'statusstatus')
    if (status == 5) {
      this.getMyOrderListFn(1).then(res => {
        this.setData({
          waitOrder: res,
          status: 5
        })
      })
    }
    if (status == 10) {
      this.getMyOrderListFn(2).then(res => {
        this.setData({
          waitUse: res,
          status: 10
        })
      })
    }
    if (status == 50) {
      this.getMyOrderListFn(3).then(res => {
        this.setData({
          finshList: res,
          status: 50
        })
      })
    }
    if (status == -1) {
      const promises = [
        this.getMyOrderListFn(1),
        this.getMyOrderListFn(2),
        this.getMyOrderListFn(3),
        this.getMyOrderListFn(5),
        this.getMyOrderListFn(6),
        this.getMyOrderListFn(600),
        this.getMyOrderListFn(-1),
        this.getMyOrderListFn(4),
      ];
      Promise.all(promises).then((results) => {
        console.log(results[6], 'results[6]')
        this.setData({
          waitOrder: results[0],
          waitUse: results[1],
          finshList: results[2],
          refoundList: results[3],
          cancelList: results[4],
          failList: results[5],
          outTimeList: results[6],
          refoundingList: results[7],
        });
      }).catch((error) => {
        console.error('获取订单列表时出错:', error);
      });
    }
    if (status == 60) {
      this.getMyOrderListFn(5).then(res => {
        this.setData({
          refoundList: res,
          status: 40
        })
      })
    }
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.getOrderList(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },


  onPullDownRefresh_(e) {
    console.log(e, '下啦')

  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    // this.refreshList(status);
    this.getMyOrderListFn()
  },

  getOrderList(statusCode = -1, reset = false) {
    const params = {
      parameter: {
        pageSize: this.page.size,
        pageNum: this.page.num,
      },
    };
    if (statusCode !== -1) params.parameter.orderStatus = statusCode;
    this.setData({
      listLoading: 1
    });
    return fetchOrders(params)
      .then((res) => {
        this.page.num++;
        let orderList = [];
        if (res && res.data && res.data.orders) {
          orderList = (res.data.orders || []).map((order) => {
            return {
              id: order.orderId,
              orderNo: order.orderNo,
              parentOrderNo: order.parentOrderNo,
              storeId: order.storeId,
              storeName: order.storeName,
              status: order.orderStatus,
              statusDesc: order.orderStatusName,
              amount: order.paymentAmount,
              totalAmount: order.totalAmount,
              logisticsNo: order.logisticsVO.logisticsNo,
              createTime: order.createTime,
              goodsList: (order.orderItemVOs || []).map((goods) => ({
                id: goods.id,
                thumb: cosThumb(goods.goodsPictureUrl, 70),
                title: goods.goodsName,
                skuId: goods.skuId,
                spuId: goods.spuId,
                specs: (goods.specifications || []).map(
                  (spec) => spec.specValue,
                ),
                price: goods.tagPrice ? goods.tagPrice : goods.actualPrice,
                num: goods.buyQuantity,
                titlePrefixTags: goods.tagText ? [{
                  text: goods.tagText
                }] : [],
              })),
              buttons: order.buttonVOs || [],
              groupInfoVo: order.groupInfoVo,
              freightFee: order.freightFee,
            };
          });
        }
        return new Promise((resolve) => {
          if (reset) {
            this.setData({
              orderList: []
            }, () => resolve());
          } else resolve();
        }).then(() => {
          this.setData({
            orderList: this.data.orderList.concat(orderList),
            listLoading: orderList.length > 0 ? 0 : 2,
          });
        });
      })
      .catch((err) => {
        this.setData({
          listLoading: 3
        });
        return Promise.reject(err);
      });
  },

  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  onTabChange(e) {
    const {
      value
    } = e.detail;
    console.log(e, 'value')
    if (value == 5) {
      this.getMyOrderListFn(1).then(res => {
        this.setData({
          waitOrder: res,
          status: 5
        })
      })
    }
    if (value == 10) {
      this.getMyOrderListFn(2).then(res => {
        this.setData({
          waitUse: res,
          status: 10
        })
      })
    }
    if (value == 50) {
      this.getMyOrderListFn(3).then(res => {
        this.setData({
          finshList: res,
          status: 50
        })
      })
    }
    if (value == 40) {
      this.getMyOrderListFn(5).then(res => {
        this.setData({
          refoundList: res,
          status: 40
        })
      })
    }
    if (value == -1) {
      this.getMyOrderListFn().then(res => {
        this.setData({
          allOrderList: res,
          status: -1
        })
      })
    }


    // this.refreshList(value);
  },
  cancel(e) {
    const id = e.currentTarget.dataset.item.id
    console.log(id, 'iddd')
    cancelOrder({
      orderId: id,
      status: 6,
    }).then(res => {
      if (res.code == 200) {
        console.log('quxiao')
        this.getMyOrderListFn(1).then(res => {
          this.setData({
            waitOrder: res,
            status: 5
          })
        })
        wx.showToast({
          title: '取消成功',
          icon: 'none',
          duration: 1000
        })

      }
    })
  },
  goToPage() {
    console.log('2212')
    wx.switchTab({
      url: '/pages/cart/index',
    })
  },

  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const {
        tabs
      } = this.data;
      console.log(tabs, 'tabs')
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({
        tabs
      });
    });
  },

  // refreshList(status = -1) {
  //   this.page = {
  //     size: this.page.size,
  //     num: 1,
  //   };
  //   this.setData({
  //     curTab: status,
  //     orderList: []
  //   });

  //   return Promise.all([
  //     this.getOrderList(status, true),
  //     // this.getOrdersCount(),
  //   ]);
  // },

  // onRefresh() {
  //   this.refreshList(this.data.curTab);
  // },

  onOrderCardTap(e) {
    const {
      order
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/order-detail/index`,
    });
  },

  goPay(e) {
    console.log(e.currentTarget.dataset.item, 'item')
    const id = e.currentTarget.dataset.item.id
    this.setData({
      orderId: id
    })
    const orderSn = e.currentTarget.dataset.item.orderSn
    this.placeOrderFn(orderSn)
  },
  async placeOrderFn(orderSn) {
    getPreOrder({
      orderSn: orderSn
    }).then(res => {
      console.log(res.data,
        'w d ')
      delete res?.data.appId
      const obj = {
        ...res?.data
      }
      wx.requestPayment({
        ...obj,
        totalFee: 1,
        success: (res) => {
          // 支付成功后的回调函数  跳待使用详情页
          console.log('支付成功', res);
          const id = this.data.orderId
          const status = 10
          // 更新订单状态等操作  
          wx.navigateTo({
            url: '/pages/order/order-detail/index?status=' + status + '&id=' + id,
          })
        },
        fail: (res) => {
          // 支付失败后的回调函数  跳待支付详情页
          console.log('支付失败', this.data, this.data.orderId, );
          // 处理支付失败的情况  
          console.log(id, 'ididid')
          const id = this.data.orderId
          console.log(id, 'ididid')
          const status = 5
          wx.navigateTo({
            url: '/pages/order/order-detail/index?status=' + status + '&id=' + id,
          })
        }
      });
    })
  },
  goToPay(e) {
    const status = e.currentTarget.dataset.status;
    const id = e.currentTarget.dataset.item.id
    // console.log(e.currentTarget.dataset, 'status11')
    wx.navigateTo({
      url: '/pages/order/order-detail/index?status=' + status + '&id=' + id,
    })
  },
  async getMyOrderListFn(orderStatus = '-1,1,2,3,4,5,600') {
    const token = wx.getStorageSync('user_token');
    if (token) {
      const res = await getMyOrderList({
        orderStatus: orderStatus,
        pageNum: 1,
        pageSize: 20,
      })
      return res.data.item
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })
    }
  }
});